# @Time : 2024-11-14 14:00
# @Author : Fioman 
# @Phone : 13149920693
"""
解析Eap的响应内容
"""
import json

from db_tools.db_handler import DbHandler
from eap_control.data_model import DataResult, EapConstant, ClockType
from eap_control.eap_config import EapConfig
from eap_control.eap_debug import debug_eap
from tools.send_to_ui_tools import (update_msg_receive, update_msg_response,
                                    update_current_user_id)

db = DbHandler()
ec = EapConfig()


def parse_response_text_normal(res_data):
    """
    解析普通的不带response_body的消息,只有response_head的消息
    如果消息格式错误,就返回response format error
    @return:
    """
    if isinstance(res_data, dict) and "response_head" in res_data:
        response_head = res_data.get("response_head")
        if (response_head is not None and "result" in response_head and "rtn_code" in response_head
                and "rtn_msg" in response_head):
            result = response_head.get("result", "")
            rtn_code = response_head.get("rtn_code", "")
            rtn_msg = response_head.get("rtn_msg", "")
            return result, rtn_code, rtn_msg
    return "resError", "", ""


def parse_cim_mode_report_response(response) -> DataResult:
    """
    解析接收到 CIMModeChangeReport 的 response,response是最原始的内容
    @param response:
    @return:
    """
    parseResult = DataResult()
    request_method = "CIMModeChangeReport"
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)
                if result.upper() != "OK":
                    parseResult.state = False
                    parseResult.info = "Eap回复NG,Local -> Remote 模式切换失败"
                    return parseResult
                else:
                    parseResult.state = True
                    parseResult.info = "Eap回复OK,Local -> Remote 模式切换成功"
    except Exception as e:
        debug_eap("in parse_cim_mode_report_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_alarm_report_response(response):
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)
    except Exception as e:
        print("in parse_status_change_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult

def parse_status_change_response(response):
    """
    解析接收到 StatusChangeReport 的 response,response是最原始的内容,不包含response_body内容
    @param response:
    @return:
    """
    request_method = "StatusChangeReport"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)
    except Exception as e:
        print("in parse_status_change_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_are_you_there_response(response):
    """
    解析are_you_there的Response
    @return:
    """
    request_method = "AreYouThere"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)
                parseResult.ino = result
                parseResult.state = True if result.upper() == "OK" else False
    except Exception as e:
        print("in parse_are_you_there_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
        parseResult.info = str(e)
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_job_count_report_response(response):
    request_method = "JobCountReport"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)

    except Exception as e:
        print("in parse_job_count_report_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_param_verify_response_text(res_data):
    """
    即系param_verify的响应内容
    @param res_data:
    @return:
    """
    """
        解析带有其他参数的response_body消息,这里是获取制程参数的一些信息
        @param res_data:
        @return:
        """
    # 默认有一个key值,不然table那里会显示出来异常,每个key可以区分每组数据,但是这里实际上只有一组数据
    res_body = {"key": "1"}
    result = "resError"
    rtn_code = ""
    rtn_msg = ""
    if isinstance(res_data, dict) and "response_head" in res_data:
        response_head = res_data.get("response_head")
        if (response_head is not None and "result" in response_head and "rtn_code"
                in response_head and "rtn_msg" in response_head):
            result = response_head.get("result", "")
            rtn_code = response_head.get("rtn_code", "")
            rtn_msg = response_head.get("rtn_msg", "")
            response_body = res_data.get("response_body", {})
            res_body["lot_id"] = response_body.get("lot_id", "default")
            res_body["prod_id"] = response_body.get("lot_id", "default")
            res_body["lot_qty"] = response_body.get("lot_id", "default")
            res_body["lot_short_id"] = response_body.get("lot_id", "default")
            res_body["prod_version"] = response_body.get("lot_id", "default")
            res_body["process_code"] = response_body.get("lot_id", "default")
            res_body["use_in_name"] = response_body.get("lot_id", "default")
            res_body["layer"] = response_body.get("layer", "default")
            res_body["step_seq"] = response_body.get("step_seq", "default")
            res_body["route_type"] = response_body.get("route_type", "default")
            res_body["rework_route_id"] = response_body.get("rework_route_id", "default")
            res_body["rework_step_seq"] = response_body.get("rework_step_seq", "default")
            res_body["pnl_side"] = response_body.get("pnl_side", "default")
            res_body["recipe_id"] = response_body.get("recipe_id", "default")
            lot_infos = response_body.get("lot_infos", {})
            lotList = lot_infos.get("lot", [
                {"item_id": "S001", "item_value": "default_600"},
                {"item_id": "S002", "item_value": "default_560"},
                {"item_id": "S003", "item_value": "default_1/3"},
                {"item_id": "S004", "item_value": "default_15"},
                {"item_id": "S005", "item_value": "default_4"},
            ])
            if len(lotList) == 0:
                lotList = [
                    {"item_id": "S001", "item_value": "default_600"},
                    {"item_id": "S002", "item_value": "default_560"},
                    {"item_id": "S003", "item_value": "default_1/3"},
                    {"item_id": "S004", "item_value": "default_15"},
                    {"item_id": "S005", "item_value": "default_4"},
                ]
            for item in lotList:
                item_id, item_value = item.get("item_id"), item.get("item_value")
                if item_id == "S001":
                    res_body["S001"] = item_value
                elif item_id == "S002":
                    res_body["S002"] = item_value
                elif item_id == "S003":
                    res_body["S003"] = item_value
                elif item_id == "S004":
                    res_body["S004"] = item_value
                elif item_id == "S005":
                    res_body["S005"] = item_value
            return result, rtn_code, rtn_msg, res_body
    return result, rtn_code, rtn_msg, res_body


def parse_param_verify_response(response):
    """
     解析接收到 ParamVerify 的 response,response包括一些信息
    @param response:
    @return:
    """
    request_method = "ParamVerify"
    result, rtn_code, rtn_msg = "无响应", "", ""
    res_body = {}
    json_dict = {}
    try:
        if response == "TimeOut":
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
            else:
                result, rtn_code, rtn_msg, res_body = parse_param_verify_response_text(json_dict)
                debug_eap(f"Send: {request_method},response_text: {response_text}"
                          f",result:{result}")
    except Exception as e:
        print("in parse_param_verify_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return res_body


def parse_real_status_change_response(response):
    """
    解析 RealStatusReport 的Response
    @return:
    """
    request_method = "RealStatusReport"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)

    except Exception as e:
        print("in parse_real_status_change_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_user_verify_response_text(res_data):
    """
     解析带有其他参数的response_body消息,这里是获取制程参数的一些信息
     @param res_data:
     @return:
     """
    # 默认有一个key值,不然table那里会显示出来异常,每个key可以区分每组数据,但是这里实际上只有一组数据
    res_body = {"key": "1"}
    result = "resError"
    rtn_code = ""
    rtn_msg = ""
    if isinstance(res_data, dict) and "response_head" in res_data:
        response_head = res_data.get("response_head")
        if (response_head is not None and "result" in response_head and "rtn_code"
                in response_head and
                "rtn_msg" in response_head):
            result = response_head.get("result", "")
            rtn_code = response_head.get("rtn_code", "")
            rtn_msg = response_head.get("rtn_msg", "")
            if result.upper() == "OK":
                response_body = res_data.get("response_body", {})
                res_body["clock_type"] = response_body.get("clock_type", "default")
                res_body["user_id"] = response_body.get("user_id", "default")
                res_body["user_name"] = response_body.get("user_name", "default")
                res_body["dept_id"] = response_body.get("dept_id", "default")
                res_body["shift_id"] = response_body.get("shift_id", "default")
                res_body["nick_name"] = response_body.get("nick_name", "default")
            return result, rtn_code, rtn_msg, res_body
    return result, rtn_code, rtn_msg, res_body


def parse_user_verify_response(userId, clock_type, response):
    """
    解析接收到的PramaVerify的response,response包括的一些信息
    @param response:
    @return:
    """
    request_method = "UserVerify"
    result, rtn_code, rtn_msg = "无响应", "", ""
    res_body = {}
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
            else:
                result, rtn_code, rtn_msg, res_body = parse_user_verify_response_text(json_dict)
    except Exception as e:
        print("in parse_param_verify_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        if result.upper() == "OK":
            # 如果返回的结果是OK,并且类型是登录
            clock_type_mes = res_body.get("clock_type", "default")
            user_id = res_body.get("user_id", "defalut")
            user_name = res_body.get("user_name", "default")
            dept_id = res_body.get("dept_id", "default")
            shift_id = res_body.get("shift_id", "default")
            nick_name = res_body.get("nick_name", "default")
            if clock_type == ClockType.I.name:
                # 如果登录,更新数据库
                new_data = {
                    "user_id": userId,
                    "user_name": user_name,
                    "dept_id": dept_id,
                    "shift_id": shift_id,
                    "nick_name": nick_name,
                }
                db.update_eap_uer_info(new_data)
                ec.reload_eap_user_login_info()
                update_current_user_id(ec.userId)
                return "ok", "登录成功"
            elif clock_type == ClockType.O.name:
                # 如果是登出,更新数据库
                new_data = {
                    "user_id": "",
                    "user_name": "",
                    "dept_id": "",
                    "shift_id": "",
                    "nick_name": "",
                }
                db.update_eap_uer_info(new_data)
                ec.reload_eap_user_login_info()
                update_current_user_id(ec.userId)
                return "ok", "登出成功"
            else:
                # 如果是查询就返回查询后的结果
                return "ok", [res_body]
        else:
            if clock_type == ClockType.I.name:
                # 如果登录,更新数据库
                return "errror", "登录失败:" + rtn_msg
            elif clock_type == ClockType.O.name:
                return "error", "登出失败:" + rtn_msg
            else:
                # 如果是查询就返回查询后的结果
                return "error", "查询失败:" + rtn_msg


def parse_wip_tracking_response(response):
    request_method = "WIPTrackingReport"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)

    except Exception as e:
        print("in parse_wip_tracking_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_utility_response(response):
    request_method = "UtilityReport"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)

    except Exception as e:
        print("in parse_utility_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_eqp_current_lot_report(response):
    request_method = "EquipmentCurrentLotReport"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)

    except Exception as e:
        print("in parse_eqp_current_lot_report() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult


def parse_utility_report_response(response):
    request_method = "UtilityReport"
    parseResult = DataResult()
    result, rtn_code, rtn_msg = "无响应", "", ""
    json_dict = {}
    try:
        if response == EapConstant.TimeOut:
            debug_eap(f"Send: {request_method},Response: {response},超时错误")
            result = response
            parseResult.info = result
        else:
            response_code = response.status_code
            response_text = response.text
            json_dict = json.loads(response_text)
            if response_code != 200:
                debug_eap(f"Send: {request_method},Response: {response},"
                          f"状态码错误: {response_code}")
                result, rtn_code, rtn_msg = f"status_code Err: {response_code}", "", ""
                parseResult.info = result
            else:
                result, rtn_code, rtn_msg = parse_response_text_normal(json_dict)

    except Exception as e:
        print("in parse_utility_report_response() error: {}".format(str(e)))
        result, rtn_code, rtn_msg = str(e), "", ""
    finally:
        update_msg_receive(json_dict)
        update_msg_response([result, rtn_code, rtn_msg])
        return parseResult
